package service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import dao.UserDao;
import utils.JdbcUtil;
import model.EventFieldsCondition;
import model.User;
import model.UserEvent;

public class EventFieldConditionService {
	public static int register(UserEvent ue,EventFieldsCondition efc,EventFieldsCondition efcLocation){
		int count = 0;
		Connection con =null;  
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        PreparedStatement pstmt3 = null;
        try {
			con = JdbcUtil.getCon();
			con.setAutoCommit(false);
			String sql1="insert into t_userEvent(uid,etId,tId,[desc],pollingTime,customTime,timeSpan,type) values(?,?,?,?,?,?,?,?)";
			pstmt1 = con.prepareStatement(sql1);
			pstmt1 = con.prepareStatement(sql1,Statement.RETURN_GENERATED_KEYS);
			pstmt1.setInt(1, ue.getuId());
			pstmt1.setInt(2, ue.getEtId());
			pstmt1.setInt(3, ue.gettId());
			pstmt1.setString(4, ue.getDesc());
			pstmt1.setInt(5, ue.getPollingTime());
			pstmt1.setString(6, ue.getCustomTime());
			pstmt1.setInt(7, ue.getTimeSpan());
			pstmt1.setString(8, ue.getType());
			
			int count1 = pstmt1.executeUpdate();
			if(count1<=0){
				throw new SQLException("插入UserEvent表失败");
			}
			ResultSet rsInsert = pstmt1.getGeneratedKeys();
			if(rsInsert!=null&&rsInsert.next()){
				
				int ueid = rsInsert.getInt(1);
				
				String sql2 = "insert into t_eventFieldsCondition(fid,ueid,condition,value) values(?,?,?,?)";
				pstmt2 = con.prepareStatement(sql2);
				pstmt2.setInt(1, efc.getfId());
				pstmt2.setInt(2, ueid);
				pstmt2.setString(3, efc.getCondition());
				pstmt2.setString(4, efc.getValue());
				
				//pstmt.setString(5, efc.getLocationValue());
				
				
				String sql3 = "insert into t_eventFieldsCondition(fid,ueid,condition,value) values(?,?,?,?)";
				pstmt3 = con.prepareStatement(sql3);
				pstmt3.setInt(1, efcLocation.getfId());
				pstmt3.setInt(2, ueid);
				pstmt3.setString(3, efcLocation.getCondition());
				pstmt3.setString(4, efcLocation.getValue());
				
				pstmt2.executeUpdate();
				count = pstmt3.executeUpdate();
				
			}
			con.commit();
			System.out.println("插入成功");
			
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				con.rollback();
				System.out.println("插入失败");
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}finally{
			JdbcUtil.closeAll(pstmt1,pstmt2,con);
		}
        
		return count;
	}

}
